package com.test

object YUVConvert {
	def  nv21_to_rgb(src: Array[Short], width: Int): Array[Short] = {
		val srcLength = src.length
		val ys = src take (srcLength * 2 / 3)
		val uvs = src takeRight (srcLength /3 )
		ys.indices.toArray flatMap  {
			index =>
				val row = index / width
				val col = index % width
				val uvRow = row / 2
				val uvCol = col / 2
				val uvIndex = uvRow * width + uvCol * 2
				val v = uvs(uvIndex)
				val u = uvs(uvIndex + 1)
				val y = ys(index)
				YUV2RGB(y, u , v)
		}
	}

	def YUV2RGB(y:Short, u:Short, v:Short):Array[Short] = {
		val rFloat = y + 1.402f * (v - 128)
		val gFloat = y - 0.344f * (u - 128) - 0.714f * (v - 128)
		val bFloat = y + 1.772f*(u - 128)
		Array(rFloat.rgbValue, gFloat.rgbValue, bFloat.rgbValue)
	}

	implicit class RichFloat(val fValue:Float) extends AnyVal {
		def rgbValue:Short = Math.min(Math.max(0, Math.round(fValue)), 255).toShort
	}
}
